<template>
  <div :class="[us.b()]">
    <van-tabs :class="[us.e('tab')]"
              v-model:active="tabActive"
              @change="tabChange">
      <tabsRender/>
    </van-tabs>
    <van-swipe :class="[us.e('swip')]"
               ref="refSwip" @change="swipChange"
               :show-indicators="false" :loop="false">
      <swip-render/>
    </van-swipe>
  </div>
</template>
<script setup>
import {computed, getCurrentInstance, h, nextTick, shallowRef, useSlots} from 'vue';
import {SwipeItem, Tab} from 'vant';
import {isEmpty, useNamespace} from '@utils';

let us = useNamespace('swip-tab');
const instance = getCurrentInstance();
const slots = useSlots();
const emits = defineEmits(['change', 'update:active']);
defineOptions({
  name: 'SwipTab'
});
const props = defineProps({
  active: {
    type: String,
    default: undefined
  }
});
const refSwip = shallowRef();

function getPanelNames() {
  return getPanelSlots().map(p => p.props.name);
}

const innerNav = shallowRef();
const tabActive = computed({
  get() {
    let names = getPanelNames();
    if (isEmpty(innerNav)) {
      innerNav.value = names[0];
    }
    return isEmpty(props.active) ? innerNav.value : props.active;
  },
  set(val) {
    emits('update:active', val);
    innerNav.value = val;
  },
});

function tabChange() {
  nextTick(() => {
    refSwip.value.swipeTo(getPanelNames().indexOf(tabActive.value), {
      immediate: true
    });
  });
}

function swipChange(val) {
  tabActive.value = getPanelNames()[val];
  emits('change', tabActive.value);
}

const swipRender = () => {
  let panelSlots = getPanelSlots();
  return panelSlots.map((p, index) => h(SwipeItem, {
    'class': [us.e('swip-item')],
    ...p.props
  }, () => p.children.default()));
};

function getPanelSlots() {
  if(!slots.default) return [];
  return slots.default().filter(s => s.type.name === "SwipTabPanel");
}

const tabsRender = () => {
  let panelSlots = getPanelSlots();
  return panelSlots.map((p, index) =>
      h(Tab, {name: p.props.name, title: p.props.title}));
};
</script>
